package cn.yangliu.config.custom;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Objects;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * @author 杨柳
 * @date 2019-06-02
 */
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {


    public static final String tokenHeadName = "Authorization";
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private TokenGenerator tokenGenerator;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        String token = request.getHeader(tokenHeadName);


        if (StringUtils.isEmpty(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        Authentication authentication = tokenStore.getAuthentication(token);

        if (Objects.isNull(authentication)) {
            filterChain.doFilter(request, response);
            return;
        }



        SecurityContextHolder.getContext().setAuthentication(authentication);

        boolean flag = tokenStore.remove(token);
        if (flag){
            token = tokenGenerator.generate(authentication);
            tokenStore.store(token,authentication);
        }
        response.setHeader(tokenHeadName,token);
        filterChain.doFilter(request, response);

    }
}
